package com.heisenhub.file.controller;

/**
 * @author sen
 * @description
 * @date 2024/2/27 10:44
 */

import com.heisenhub.common.oauth.annotation.ApiResourceOpen;
import com.heisenhub.file.common.dto.FileDto;
import com.heisenhub.file.domin.FileStorageManager;
import com.heisenhub.file.entity.OpFile;
import com.heisenhub.file.service.IOpFileService;
import com.heisnenhub.common.module.exception.RRException;
import com.heisnenhub.common.module.utils.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.List;


@RestController
@RequestMapping("/file")
@Slf4j
public class FileController {


    @Autowired
    private FileStorageManager fileStorageManager;

    @Autowired
    private IOpFileService opFileService;


    @PostMapping("/uploadFile")
    @ApiResourceOpen
    public Api uploadFile(@RequestParam(value = "files", required = true) MultipartFile[] files , FileDto fileDto) {
        log.info("【准备文件上传】 fileDto={}",fileDto);
        if(StringUtils.isEmpty(fileDto.getStoreService())) throw new RRException("服务名称为空");
        return Api.ok(fileStorageManager.upload(files ,fileDto));
    }

    @GetMapping("/fileUrl")
    @ApiResourceOpen
    public Api fileUrl(@RequestParam(value = "fileId")String fileId ) {
        log.info("【获取文件url】fileId: {}",fileId);
        return Api.ok( fileStorageManager.fileUrl(fileId));
    }


    @GetMapping("/delete")
    @ApiResourceOpen
    public Api delete(@RequestParam(value = "fileId")String fileId ) {
        log.info("【准备文件删除】fileId: {}",fileId);
        return Api.of(fileStorageManager.delete(fileId)).build();
    }

    @GetMapping("/download")
    @ApiResourceOpen
    public void download(@RequestParam(value = "fileId")String fileId, HttpServletResponse response) {
        log.info("【准备文件下载】fileId: {}",fileId);
        fileStorageManager.download(fileId,response);
    }


    @GetMapping("/image")
    @ApiResourceOpen
    public Api downloadImage() {
        try {
            // 确保目标文件夹存在
            Path directory = Paths.get("C:\\Users\\Administrator\\Pictures\\Camera Roll");
            if (!Files.exists(directory)) {
                Files.createDirectories(directory);
            }

            List<OpFile> list = opFileService.list();
            for (OpFile opFile : list) {
                // 解析文件名
                String fileName = opFile.getOriginalName();
                Path targetPath = directory.resolve(fileName);

                String imageUrl = fileStorageManager.fileUrl(String.valueOf(opFile.getId()));

                // 下载图片
                URL url = new URL(imageUrl);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");

                InputStream inputStream = connection.getInputStream();
                Files.copy(inputStream, targetPath, StandardCopyOption.REPLACE_EXISTING);

                log.info("【图片已成功下载 文件名：】" ,fileName);

            }
            return Api.ok("图片全部成功下载好了" );
        } catch (IOException e) {
            e.printStackTrace();
            return Api.fail("下载图片失败: " + e.getMessage());
        }
    }


}
